﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using DevExpress.UserSkins;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraBars.Helpers;
using CNotebook;
using CNotebook.Sales;

namespace NotebookS2
{
    public partial class CashReceipt : RibbonForm
    {
        public CashReceipt()
        {
            InitializeComponent();
        }

        DataTable InitializeDeductions()
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("Particulars", typeof(string));
            dt.Columns.Add("AcctCode", typeof(string));
            dt.Columns.Add("AcctName", typeof(string));
            dt.Columns.Add("Amount", typeof(double));

            return dt;
        }

        void ComputeTotal()
        {
            double _TotalInvoice = 0;
            double _TotalReturns = 0;
            double _TotalDeductions = 0;
            foreach (DataRow oRow in this.InvoiceLineItems.Rows)
            {
                if (oRow["AppliedAmount"] != DBNull.Value)
                {
                    _TotalInvoice = _TotalInvoice + Convert.ToDouble(oRow["AppliedAmount"]);
                }
            }

            foreach (DataRow oRow in this.DeductionAndExpensesLineItems.Rows)
            {

                if (oRow["Amount"] != DBNull.Value)
                {
                    _TotalDeductions = _TotalDeductions + Convert.ToDouble(oRow["Amount"]);
                }
            }

            foreach (DataRow oRow in this.ReturnLineItems.Rows)
            {

                if (oRow["AppliedAmount"] != DBNull.Value)
                {
                    _TotalReturns = _TotalReturns + Convert.ToDouble(oRow["AppliedAmount"]);
                }
            }
            txtTotalApplied.Text = (_TotalInvoice - (_TotalDeductions+_TotalReturns)).ToString();

            txtTotalBalance.Text = (((_TotalInvoice - (_TotalDeductions + _TotalReturns))) - (this.CashAmount + this.CheckAmount + this.FundTransferAmount)).ToString("#,###.00");

            //if (((this.CashAmount + this.CheckAmount + this.FundTransferAmount) - ((_TotalInvoice - (_TotalDeductions + _TotalReturns)))) == 0)
            //{
            //    foreach (DevExpress.XtraGrid.Columns.GridColumn oColumn in gridView1.Columns)
            //    {
            //        oColumn.OptionsColumn.AllowEdit = false;
            //    }

            //    foreach (DevExpress.XtraGrid.Columns.GridColumn oColumn in gridView2.Columns)
            //    {
            //        oColumn.OptionsColumn.AllowEdit = false;
            //    }
            //    foreach (DevExpress.XtraGrid.Columns.GridColumn oColumn in gridView3.Columns)
            //    {
            //        oColumn.OptionsColumn.AllowEdit = false;
            //    }

            //    btnAdd.Enabled = false;
            //}

        }

        DataTable InitializeAppliedInvoices()
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("DocType", typeof(string));
            dt.Columns.Add("InvoiceNumber", typeof(string));
            dt.Columns.Add("Reference", typeof(string));
            dt.Columns.Add("Amount", typeof(double));
            dt.Columns.Add("AppliedAmount", typeof(double));

            return dt;
        }

        DataTable InitializeAppliedReturns()
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("ReturnNo", typeof(string));
            dt.Columns.Add("Amount", typeof(double));
            dt.Columns.Add("AppliedAmount", typeof(double));

            return dt;
        }

        DataTable InitializeCheckLineItems()
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("CheckAcctCode", typeof(string));
            dt.Columns.Add("CheckAcctName", typeof(string));
            dt.Columns.Add("BankName", typeof(string));
            dt.Columns.Add("CheckNumber", typeof(string));
            dt.Columns.Add("CheckAmount", typeof(double));
            dt.Columns.Add("CheckDate", typeof(DateTime));
            dt.Columns.Add("CheckStatus", typeof(string));

            return dt;
        }

        public DataTable ReturnLineItems { get; set; }
        public DataTable InvoiceLineItems { get; set; }
        public DataTable DeductionAndExpensesLineItems { get; set; }
        public DataTable CheckLineItems { get; set; }

        public const int ObjectType = 16;
        public string ActiveUserID { get; set; }
        public string ConnectionString { get; set; }

        public string CashGLAcctCode { get; set; }
        public string CashGLAcctName { get; set; }
        public double CashAmount { get; set; }

        public string CheckGLAcctCode { get; set; }
        public string CheckGLAcctName { get; set; }
        public double CheckAmount { get; set; }

        public string FundTransferAcctCode { get; set; }
        public string FundTransferAcctName { get; set; }
        public string FundTransferBank { get; set; }
        public string FundTransferReference { get; set; }
        public DateTime FundTransferDate { get; set; }
        public double FundTransferAmount { get; set; }


        void RemoveDeductionLastRowFirst()
        {
            try
            {
                gridView1.MoveLast();
                string sItemCode = "";


                sItemCode = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["AcctCode"]).ToString();

                if (sItemCode.Trim() == "")
                {
                    gridView1.DeleteRow(gridView1.FocusedRowHandle);
                }
            }
            catch
            {
            }

        }

        void RemoveInvoiceLastRowFirst()
        {
            try
            {

                gridView2.MoveLast();


                string sItemCode = "";


                sItemCode = gridView2.GetRowCellValue(gridView2.FocusedRowHandle, gridView2.Columns["InvoiceNumber"]).ToString();

                if (sItemCode.Trim() == "")
                {
                    gridView2.DeleteRow(gridView2.FocusedRowHandle);
                }
            }
            catch
            {
            }

        }

        void RemoveReturnLastRowFirst()
        {
            try
            {

                gridView3.MoveLast();

                string sItemCode = "";


                sItemCode = gridView3.GetRowCellValue(gridView3.FocusedRowHandle, gridView3.Columns["ReturnNo"]).ToString();

                if (sItemCode.Trim() == "")
                {
                    gridView3.DeleteRow(gridView3.FocusedRowHandle);
                }
            }
            catch
            {
            }

        }

        void PostDocument(string _DocNumber)
        {
            CashReceiptManager oManager = new CashReceiptManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            oManager.PostDocument(_DocNumber);

            oManager.Close();

            txtStatus.Text = "Posted";


            foreach (DataRow oRow in this.InvoiceLineItems.Rows)
            {
                if (oRow["DocType"].ToString() == "DR/Invoice")
                {
                    InvoiceManager oInvoiceManager = new InvoiceManager();

                    oInvoiceManager.ConnectionString = this.ConnectionString;
                    oInvoiceManager.Open();

                    oInvoiceManager.SetAppliedAmount(oRow["InvoiceNumber"].ToString(), oRow["AppliedAmount"].ToString());

                    oInvoiceManager.Close();
                }

                if (oRow["DocType"].ToString() == "A/R Debit Memo")
                {
                    DebitMemoManager oDebitMemoManager = new DebitMemoManager();

                    oDebitMemoManager.ConnectionString = this.ConnectionString;
                    oDebitMemoManager.Open();

                    oDebitMemoManager.SetAppliedAmount(oRow["InvoiceNumber"].ToString(), oRow["AppliedAmount"].ToString());

                    oDebitMemoManager.Close();
                }

                if (oRow["DocType"].ToString() == "A/R Credit Memo")
                {
                    CreditMemoManager oCreditMemoManager = new CreditMemoManager();

                    oCreditMemoManager.ConnectionString = this.ConnectionString;
                    oCreditMemoManager.Open();

                    oCreditMemoManager.SetAppliedAmount(oRow["InvoiceNumber"].ToString(), oRow["AppliedAmount"].ToString());

                    oCreditMemoManager.Close();
                }
            }

        }

        void CancelDocument(string _DocNumber)
        {
            CashReceiptManager oManager = new CashReceiptManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            oManager.CancelDocument(_DocNumber);

            oManager.Close();
            txtStatus.Text = "Canceled";
        }

        void CloseDocument(string _DocNumber)
        {
            CashReceiptManager oManager = new CashReceiptManager();

            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            oManager.CloseDocument(_DocNumber);

            oManager.Close();

            txtStatus.Text = "Closed";
        }

        void InitializeSeries()
        {
            string ObjectType = "16";
            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();


            if (oSeries.IsAutoNumber(ObjectType) == true)
            {
                txtDocNum.Properties.ReadOnly = true;
                txtDocNum.Text = "##########";

            }
            oSeries.Close();
        }

        string GetNewSeries()
        {
            string _SERIES = "";
            string _OBJECT_TYPE = "16";

            SeriesManager oSeries = new SeriesManager();
            oSeries.ConnectionString = this.ConnectionString;
            oSeries.Open();
            if (oSeries.IsAutoNumber(_OBJECT_TYPE) == true)
            {
                _SERIES = oSeries.GetNewSeries(_OBJECT_TYPE);
            }
            else
            {
                _SERIES = txtDocNum.Text;
            }
            oSeries.Close();

            return _SERIES;
        }

        void DisableControls()
        {
            radioSelection.Enabled = false;
            txtReference.Enabled = false;
            txtDocNum.Enabled = false;

            txtRemarks.Enabled = false;
            
            dtDateCreated.Enabled = false;
            txtCreatedBy.Enabled = false;
            dtDateModified.Enabled = false;
            txtModifiedBy.Enabled = false;
            cboDocType.Enabled = false;
            txtReceiptNumber.Enabled = false;
            dtPostingDate.Enabled = false;
            txtTINNumber.Enabled = false;
            txtCustCode.Enabled = false;
            txtCustName.Enabled = false;
            txtAddress.Enabled = false;
            //txtCashAmount.Enabled = false;


            //foreach (DevExpress.XtraGrid.Columns.GridColumn oColumn in gridView1.Columns)
            //{
            //    oColumn.OptionsColumn.AllowEdit = false;
            //}

            //foreach (DevExpress.XtraGrid.Columns.GridColumn oColumn in gridView2.Columns)
            //{
            //    oColumn.OptionsColumn.AllowEdit = false;
            //}
            //foreach (DevExpress.XtraGrid.Columns.GridColumn oColumn in gridView3.Columns)
            //{
            //    oColumn.OptionsColumn.AllowEdit = false;
            //}

        }

        void EnableControls()
        {
            txtDocNum.Enabled = true;
            radioSelection.Enabled = true;
            txtReference.Enabled = true;
            txtRemarks.Enabled = true;
            
            dtDateCreated.Enabled = true;
            txtCreatedBy.Enabled = true;
            dtDateModified.Enabled = true;
            txtModifiedBy.Enabled = true;
            cboDocType.Enabled = true;
            txtReceiptNumber.Enabled = true;
            dtPostingDate.Enabled = true;
            txtTINNumber.Enabled = true;
            txtCustCode.Enabled = true;
            txtCustName.Enabled = true;
            txtAddress.Enabled = true;
            //txtCashAmount.Enabled = true;

            //foreach (DevExpress.XtraGrid.Columns.GridColumn oColumn in gridView1.Columns)
            //{
            //    oColumn.OptionsColumn.AllowEdit = true;
            //}

            //foreach (DevExpress.XtraGrid.Columns.GridColumn oColumn in gridView2.Columns)
            //{
               
            //   oColumn.OptionsColumn.AllowEdit = true;
               
            //}
            //foreach (DevExpress.XtraGrid.Columns.GridColumn oColumn in gridView3.Columns)
            //{
            //    oColumn.OptionsColumn.AllowEdit = true;
            //}

        }

        public void ShowSearch()
        {
            FND_CASHRECEIPT oForm = new FND_CASHRECEIPT();
            oForm.DocumentType = cboDocType.Text;
            oForm.ConnectionString = this.ConnectionString;
            oForm.ShowDialog();

            CashReceiptManager oManager = new CashReceiptManager();
            DataTable dt = new DataTable();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            dt = oManager.GetCashEntry(oForm.SelectedDocumentNumber);

            oManager.Close();

            DataRow oRow = dt.Rows[0];

            txtDocNum.Text = oRow["DocNum"].ToString();
            txtReference.Text = oRow["Reference"].ToString();
            txtRemarks.Text = oRow["Remarks"].ToString();
            cboDocType.Text = oRow["DocType"].ToString();
            txtReceiptNumber.Text = oRow["ReceiptNumber"].ToString();
            dtPostingDate.EditValue = (DateTime)oRow["PostingDate"];
            txtTINNumber.Text = oRow["TINNumber"].ToString();

            radioSelection.SelectedIndex = Convert.ToInt16(oRow["PayeeIndex"]);
            txtCustCode.Text = oRow["PayeeCode"].ToString();
            txtCustName.Text = oRow["PayeeName"].ToString();
            txtAddress.Text = oRow["AddressOrRemarks"].ToString();

            #region Cash Entries
            this.CashGLAcctCode = oRow["CashAcctCode"].ToString();
            this.CashGLAcctName = oRow["CashAcctName"].ToString();
            this.CashAmount = Convert.ToDouble(oRow["CashAmount"]);
            #endregion

            #region Check Entries
            this.CheckGLAcctCode = oRow["CheckAcctCode"].ToString();
            this.CheckGLAcctName = oRow["CheckAcctName"].ToString();
            this.CheckAmount = Convert.ToDouble(oRow["CheckAmount"]);
            #endregion

            #region Bank Transfer
            this.FundTransferAcctCode = oRow["FundTrsfAcctCode"].ToString();
            this.FundTransferAcctName = oRow["FundTrsfrAcctName"].ToString();
            this.FundTransferBank = oRow["FundTrsfrBank"].ToString();
            this.FundTransferReference = oRow["FundTrsfrReference"].ToString();
            this.FundTransferDate = Convert.ToDateTime(oRow["FundTrsfrDate"]);
            this.FundTransferAmount = Convert.ToDouble(oRow["FundTrsfrAmount"]);
            #endregion

            txtTotalPayment.Text = oRow["Total"].ToString();
            txtStatus.Text = oRow["DocStatus"].ToString();
            txtCreatedBy.Text = oRow["CreatedBy"].ToString();
            dtDateCreated.EditValue = (DateTime)oRow["DateCreated"];
            txtModifiedBy.Text = oRow["ModifiedBy"].ToString();
            dtDateModified.EditValue = (DateTime)oRow["DateModified"];

            oManager = new CashReceiptManager();
            oManager.ConnectionString = this.ConnectionString;
            oManager.Open();

            this.ReturnLineItems = oManager.GetAppliedSalesReturn(txtDocNum.Text);
            this.InvoiceLineItems = oManager.GetAppliedInvoices(txtDocNum.Text);
            this.DeductionAndExpensesLineItems = oManager.GetAppliedDeduction(txtDocNum.Text);

            this.CheckLineItems = oManager.GetCheckPayments(txtDocNum.Text);

            oManager.Close();


            gridControl1.DataSource = this.DeductionAndExpensesLineItems;
            gridControl1.Refresh();

            gridControl2.DataSource = this.InvoiceLineItems;
            gridControl2.Refresh();

            gridControl3.DataSource = this.ReturnLineItems;
            gridControl3.Refresh();

            ComputeTotal();
            if (txtStatus.Text == "Draft")
            {
                if (gridView1.RowCount <= 0)
                {
                    gridView1.AddNewRow();
                }

                if (gridView2.RowCount <= 0)
                {
                    gridView2.AddNewRow();
                }

                if (gridView3.RowCount <= 0)
                {
                    gridView3.AddNewRow();
                }
            }

            btnAdd.Text = "Update";
        }


        private void CashReceipt_Load(object sender, EventArgs e)
        {
            int iZeroAmount = 0;

            #region Data Tables

            this.InvoiceLineItems = InitializeAppliedInvoices();
            this.ReturnLineItems = InitializeAppliedReturns();
            this.DeductionAndExpensesLineItems = InitializeDeductions();
            this.CheckLineItems = InitializeCheckLineItems();

            #endregion

            gridControl1.DataSource = this.DeductionAndExpensesLineItems;
            gridControl1.Refresh();

            gridControl2.DataSource = this.InvoiceLineItems;
            gridControl2.Refresh();

            gridControl3.DataSource = this.ReturnLineItems;
            gridControl3.Refresh();

            #region Cash Entries
            this.CashGLAcctCode = "";
            this.CashGLAcctName = "";

            this.CashAmount = iZeroAmount;
            #endregion

            #region Check Entries
            this.CheckGLAcctCode = "";
            this.CheckGLAcctName = "";
            this.CheckAmount = iZeroAmount;
            #endregion

            #region Bank Transfer
            this.FundTransferAcctCode = "";
            this.FundTransferAcctName = "";
            this.FundTransferBank = "";
            this.FundTransferReference = "";
            this.FundTransferDate = System.DateTime.Now;
            this.FundTransferAmount = iZeroAmount;
            #endregion
            
            cboDocType.SelectedIndex = 0;

            InitializeSeries();

            txtCreatedBy.Text = this.ActiveUserID;
            txtModifiedBy.Text = this.ActiveUserID;

            dtDateCreated.EditValue = System.DateTime.Now;
            dtDateModified.EditValue = System.DateTime.Now;
            dtPostingDate.EditValue = System.DateTime.Now;

            #region Adding New Row

            if (txtStatus.Text == "Draft")
            {
                if (gridView1.RowCount <= 0)
                {
                    gridView1.AddNewRow();
                }

                if (gridView2.RowCount <= 0)
                {
                    gridView2.AddNewRow();
                }

                if (gridView3.RowCount <= 0)
                {
                    gridView3.AddNewRow();
                }
            }

            #endregion

        }
        
        private void btnPaymentMeans_Click(object sender, EventArgs e)
        {
            PaymentMeans oForm = new PaymentMeans();

            oForm.CheckLineItems = this.CheckLineItems;
            oForm.DocumentCode = "Check Voucher";
            oForm.ConnectionString = this.ConnectionString;

            if (txtStatus.Text != "Draft")
            {
                oForm.IsReadOnly = true;
            }

            #region Cash Entries
            oForm.CashGLAcctCode = this.CashGLAcctCode;
            oForm.CashGLAcctName = this.CashGLAcctName;
            oForm.CashAmount = Convert.ToDouble(this.CashAmount);
            #endregion

            #region Check Entries
            oForm.CheckGLAcctCode = this.CheckGLAcctCode.ToString();
            oForm.CheckGLAcctName = this.CheckGLAcctName.ToString();
            oForm.CheckAmount = Convert.ToDouble(this.CheckAmount);
            #endregion

            #region Bank Transfer
            oForm.FundTransferAcctCode = this.FundTransferAcctCode;
            oForm.FundTransferAcctName = this.FundTransferAcctName;
            oForm.FundTransferBank = this.FundTransferBank;
            oForm.FundTransferReference = this.FundTransferReference;
            oForm.FundTransferDate = this.FundTransferDate;
            oForm.FundTransferAmount = this.FundTransferAmount;
            #endregion
            


            oForm.ShowDialog();


            this.CheckLineItems = oForm.CheckLineItems;

            if (oForm.IsCancelled == false)
            {
                #region Cash Entries
                this.CashGLAcctCode = oForm.CashGLAcctCode;
                this.CashGLAcctName = oForm.CashGLAcctName;
                this.CashAmount = Convert.ToDouble(oForm.CashAmount);
                #endregion

                #region Check Entries
                this.CheckGLAcctCode = oForm.CheckGLAcctCode.ToString();
                this.CheckGLAcctName = oForm.CheckGLAcctName.ToString();
                this.CheckAmount = Convert.ToDouble(oForm.CheckAmount);
                #endregion

                #region Bank Transfer
                this.FundTransferAcctCode = oForm.FundTransferAcctCode;
                this.FundTransferAcctName = oForm.FundTransferAcctName;
                this.FundTransferBank = oForm.FundTransferBank;
                this.FundTransferReference = oForm.FundTransferReference;
                this.FundTransferDate = oForm.FundTransferDate;
                this.FundTransferAmount = oForm.FundTransferAmount;
                #endregion

                txtTotalPayment.Text = (this.CashAmount + this.CheckAmount + this.FundTransferAmount).ToString();
            }

            ComputeTotal();
        }

        private void xtraScrollableControl1_Click(object sender, EventArgs e)
        {

        }

        private void btnAdd_Click(object sender, EventArgs e)
        {   
            RemoveDeductionLastRowFirst();
            RemoveInvoiceLastRowFirst();
            RemoveReturnLastRowFirst();

            double _Balance = Convert.ToDouble(txtTotalBalance.Text.Replace(",", ""));

            //if (_Balance < 0)
            //{
            //    MessageBox.Show("Balance falls to negative!!! Please check your entries!!!", "Payment", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    return;
            //}

            if (btnAdd.Text == "Add")
            {
                
                CashReceiptManager oManager = new CashReceiptManager();
                CashReceiptUnit oUnit = new CashReceiptUnit();

                txtDocNum.Text = GetNewSeries();

                oUnit.DocumentNumber = txtDocNum.Text;
                oUnit.Reference = txtReference.Text;
                oUnit.Remarks = txtRemarks.Text;
                oUnit.DocumentType = cboDocType.Text;
                oUnit.ReceiptNumber = txtReceiptNumber.Text;

                oUnit.PostingDate = (DateTime)dtPostingDate.EditValue;
                oUnit.TINNumber = txtTINNumber.Text;

                if (radioSelection.SelectedIndex == 0)
                {
                    oUnit.IsAccount = false;
                }
                else
                {
                    oUnit.IsAccount = true;
                }
                oUnit.PayeeIndex = radioSelection.SelectedIndex;
                oUnit.CardCode = txtCustCode.Text;
                oUnit.CardName = txtCustName.Text;
                oUnit.Address = txtAddress.Text;

                #region Cash Entries
                oUnit.CashGLAcctCode = this.CashGLAcctCode;
                oUnit.CashGLAcctName = this.CashGLAcctName;
                oUnit.CashAmount = Convert.ToDouble(this.CashAmount);
                #endregion

                oUnit.CheckGLAcctCode = this.CheckGLAcctCode;
                oUnit.CheckGLAcctName = this.CheckGLAcctName;
                oUnit.CheckAmount = this.CheckAmount;

                #region Bank Transfer
                oUnit.FundTransferAcctCode = this.FundTransferAcctCode;
                oUnit.FundTransferAcctName = this.FundTransferAcctName;
                oUnit.FundTransferBank = this.FundTransferBank;
                oUnit.FundTransferReference = this.FundTransferReference;
                oUnit.FundTransferDate = this.FundTransferDate;
                oUnit.FundTransferAmount = this.FundTransferAmount;
                #endregion

                oUnit.TotalAmount = Convert.ToDouble(txtTotalPayment.Text);
                oUnit.DocumentStatus = txtStatus.Text;
                oUnit.DateCreated = (DateTime)dtDateCreated.EditValue;
                oUnit.CreatedBy = txtCreatedBy.Text;
                oUnit.DateModified = (DateTime)dtDateModified.EditValue;
                oUnit.ModifiedBy = txtModifiedBy.Text;

                oUnit.AppliedDeductionAndExpenses = this.DeductionAndExpensesLineItems;
                oUnit.AppliedSalesInvoice = this.InvoiceLineItems;
                oUnit.AppliedSalesReturn = this.ReturnLineItems;

                oUnit.CheckLineItems = this.CheckLineItems;

                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();

                oManager.AddNewCashEntry(oUnit);

                oManager.Close();

                btnAdd.Text = "Update";

                MessageBox.Show("Successfully added!!!", "Cash Receipt", MessageBoxButtons.OK, MessageBoxIcon.Information);

                if (txtStatus.Text == "Draft")
                {
                    if (gridView1.RowCount <= 0)
                    {
                        gridView1.AddNewRow();
                    }

                    if (gridView2.RowCount <= 0)
                    {
                        gridView2.AddNewRow();
                    }

                    if (gridView3.RowCount <= 0)
                    {
                        gridView3.AddNewRow();
                    }
                }


            }
            else
            {
                CashReceiptManager oManager = new CashReceiptManager();
                CashReceiptUnit oUnit = new CashReceiptUnit();

                oUnit.DocumentNumber = txtDocNum.Text;
                oUnit.Reference = txtReference.Text;
                oUnit.Remarks = txtRemarks.Text;
                oUnit.DocumentType = cboDocType.Text;
                oUnit.ReceiptNumber = txtReceiptNumber.Text;

                oUnit.PostingDate = (DateTime)dtPostingDate.EditValue;
                oUnit.TINNumber = txtTINNumber.Text;

                if (radioSelection.SelectedIndex == 0)
                {
                    oUnit.IsAccount = false;
                }
                else
                {
                    oUnit.IsAccount = true;
                }
                oUnit.PayeeIndex = radioSelection.SelectedIndex;
                oUnit.CardCode = txtCustCode.Text;
                oUnit.CardName = txtCustName.Text;
                oUnit.Address = txtAddress.Text;


                #region Cash Entries
                oUnit.CashGLAcctCode = this.CashGLAcctCode;
                oUnit.CashGLAcctName = this.CashGLAcctName;
                oUnit.CashAmount = Convert.ToDouble(this.CashAmount);
                #endregion

                #region Check Entries
                oUnit.CheckGLAcctCode = this.CheckGLAcctCode.ToString();
                oUnit.CheckGLAcctName = this.CheckGLAcctName.ToString();
                oUnit.CheckAmount = Convert.ToDouble(this.CheckAmount);
                #endregion

                #region Bank Transfer
                oUnit.FundTransferAcctCode = this.FundTransferAcctCode;
                oUnit.FundTransferAcctName = this.FundTransferAcctName;
                oUnit.FundTransferBank = this.FundTransferBank;
                oUnit.FundTransferReference = this.FundTransferReference;
                oUnit.FundTransferDate = this.FundTransferDate;
                oUnit.FundTransferAmount = this.FundTransferAmount;
                #endregion
                
                oUnit.TotalAmount = Convert.ToDouble(txtTotalPayment.Text);
                oUnit.DocumentStatus = txtStatus.Text;
                oUnit.DateCreated = (DateTime)dtDateCreated.EditValue;
                oUnit.CreatedBy = txtCreatedBy.Text;
                oUnit.DateModified = (DateTime)dtDateModified.EditValue;
                oUnit.ModifiedBy = txtModifiedBy.Text;


                oUnit.CheckLineItems = this.CheckLineItems;

                oUnit.AppliedDeductionAndExpenses = this.DeductionAndExpensesLineItems;
                oUnit.AppliedSalesInvoice = this.InvoiceLineItems;
                oUnit.AppliedSalesReturn = this.ReturnLineItems;


                oManager.ConnectionString = this.ConnectionString;
                oManager.Open();

                oManager.UpdateCashEntry(oUnit);

                oManager.Close();

                MessageBox.Show("Successfully updated!!!", "Cash Receipt", MessageBoxButtons.OK, MessageBoxIcon.Information);

                if (txtStatus.Text == "Draft")
                {
                    if (gridView1.RowCount <= 0)
                    {
                        gridView1.AddNewRow();
                    }

                    if (gridView2.RowCount <= 0)
                    {
                        gridView2.AddNewRow();
                    }

                    if (gridView3.RowCount <= 0)
                    {
                        gridView3.AddNewRow();
                    }
                }

                //if (Convert.ToDouble(txtTotalBalance.Text.Replace(",", "")) == 0)
                //{
                //    oManager = new CashReceiptManager();

                //    oManager.ConnectionString = this.ConnectionString;
                //    oManager.Open();
                //    oManager.CloseDocument(txtDocNum.Text);
                //    oManager.Close();

                //    txtStatus.Text = "Closed";
                //    btnAdd.Enabled = false;
                //}

            }



        }

        private void txtCustCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (radioSelection.SelectedIndex == 1)
            {
                FND_BP _SearchBP = new FND_BP();

                AddressBookManager oBPManager = new AddressBookManager();
                TaxManager oTxManager = new TaxManager();

                try
                {


                    _SearchBP.ConnectionString = this.ConnectionString;
                    _SearchBP.BusinessPartnerType = "Customer";
                    _SearchBP.ShowDialog();

                    txtCustCode.Text = _SearchBP.CardCode;
                    txtCustName.Text = _SearchBP.CardName;
                    txtTINNumber.Text = _SearchBP.TIN;
                    txtAddress.Text = _SearchBP.Address;
                    txtAddress.Enabled = false;
                }
                catch
                {
                }
            }
            else if (radioSelection.SelectedIndex == 2)
            {
                FND_BP _SearchBP = new FND_BP();

                AddressBookManager oBPManager = new AddressBookManager();
                TaxManager oTxManager = new TaxManager();

                try
                {


                    _SearchBP.ConnectionString = this.ConnectionString;
                    _SearchBP.BusinessPartnerType = "Vendor";
                    _SearchBP.ShowDialog();

                    txtCustCode.Text = _SearchBP.CardCode;
                    txtCustName.Text = _SearchBP.CardName;
                    txtTINNumber.Text = _SearchBP.TIN;
                    txtAddress.Text = _SearchBP.Address;
                    txtAddress.Enabled = false;
                }
                catch
                {
                }
            }

            else if (radioSelection.SelectedIndex == 3)
            {
                FND_GLACCOUNT oForm = new FND_GLACCOUNT();

                oForm.ConnectionString = this.ConnectionString;
                oForm.ShowDialog();

                txtTINNumber.Text = "N/A";
                txtAddress.Enabled = true;
                txtCustCode.Text = oForm.SelectedGLAcctCode;
                txtCustName.Text = oForm.SelectedGLAcctName;

            }
        }

        private void txtStatus_EditValueChanged(object sender, EventArgs e)
        {
            if (txtStatus.Text == "Posted")
            {
                DisableControls();
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = true;
            }

            if (txtStatus.Text == "Draft")
            {
                EnableControls();
                txtStatus.Properties.Buttons[0].Visible = true;
                txtStatus.Properties.Buttons[1].Visible = true;
            }

            if (txtStatus.Text == "Canceled")
            {
                DisableControls();
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = false;
            }

            if (txtStatus.Text == "Closed")
            {
                DisableControls();
                txtStatus.Properties.Buttons[0].Visible = false;
                txtStatus.Properties.Buttons[1].Visible = false;
            }
        }

        private void radioSelection_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (radioSelection.SelectedIndex == 0)
            {
                lblSelection.Text = "Customer";
                lblAddress.Text = "Address:";

                txtCustCode.Text = "";
                txtCustName.Text = "";
                txtAddress.Text = "";
                txtTINNumber.Text = "";


            }
            else if (radioSelection.SelectedIndex == 1)
            {
                lblSelection.Text = "Branch";
                lblAddress.Text = "Address:";

                txtCustCode.Text = "";
                txtCustName.Text = "";
                txtAddress.Text = "";
                txtTINNumber.Text = "";


            }
            else if (radioSelection.SelectedIndex == 2)
            {
                lblSelection.Text = "Vendor";
                lblAddress.Text = "Address:";

                txtCustCode.Text = "";
                txtCustName.Text = "";
                txtAddress.Text = "";
                txtTINNumber.Text = "";
            }
            else if (radioSelection.SelectedIndex == 3)
            {
                lblSelection.Text = "Account";
                lblAddress.Text = "Remarks:";

                txtCustCode.Text = "";
                txtCustName.Text = "";
                txtAddress.Text = "";
                txtTINNumber.Text = "";
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtStatus_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

            switch (e.Button.Index)
            {
                case 0:
                    // Post

                    if (MessageBox.Show("Are you sure you want to post this Document?", "Post Document", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                    {
                        double _balance = Convert.ToDouble(txtTotalBalance.Text.Replace(",", ""));

                        PostDocument(txtDocNum.Text);
                       
                    }

                    break;
                case 1:
                    // Cancel:
                    if (txtStatus.Text == "Draft")
                    {
                        if (MessageBox.Show("Are you sure you want to cancel this Document?", "Cancel Document", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                        {
                            CancelDocument(txtDocNum.Text);
                        }
                    }
                    else if (txtStatus.Text == "Posted")
                    {
                        double _balance = Convert.ToDouble(txtTotalBalance.Text.Replace(",", ""));
                        if (_balance == 0)
                        {
                            if (MessageBox.Show("Are you sure you want to close this Document?", "Close Document", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
                            {
                                CloseDocument(txtDocNum.Text);
                                btnAdd.Enabled = false;
                            }
                        }
                        else
                        {
                            MessageBox.Show("Your not able to close the document if the Balance is greater than zero!!!", "Balance", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    break;
            }
        }

        private void xtraScrollableControl2_Click(object sender, EventArgs e)
        {

        }

        private void txtInvoiceNum_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            string sDocument = gridView2.GetRowCellValue(gridView2.FocusedRowHandle, gridView2.Columns["DocType"]).ToString();
            
            if (sDocument == "DR/Invoice")
            {
                FND_CASHRECEIPT_INVOICES oForm = new FND_CASHRECEIPT_INVOICES();

                oForm.ConnectionString = this.ConnectionString;
                oForm.CustomerCode = txtCustCode.Text;
                oForm.ShowDialog();

                int iFocusHandle = gridView2.FocusedRowHandle;

                gridView2.SetRowCellValue(iFocusHandle, gridView2.Columns["InvoiceNumber"], oForm.DocumentNumber);
                gridView2.SetRowCellValue(iFocusHandle, gridView2.Columns["Reference"], oForm.Reference);
                gridView2.SetRowCellValue(iFocusHandle, gridView2.Columns["Amount"], oForm.TotalBalance);
                gridView2.SetRowCellValue(iFocusHandle, gridView2.Columns["AppliedAmount"], oForm.TotalBalance);
            }

            if (sDocument == "A/R Debit Memo")
            {
                FND_CASHRECEIPT_ARDM oForm = new FND_CASHRECEIPT_ARDM();

                oForm.ConnectionString = this.ConnectionString;
                oForm.CardCode = txtCustCode.Text;
                oForm.ShowDialog();

                int iFocusHandle = gridView2.FocusedRowHandle;

                gridView2.SetRowCellValue(iFocusHandle, gridView2.Columns["InvoiceNumber"], oForm.SelectedDocumentNumber);
                gridView2.SetRowCellValue(iFocusHandle, gridView2.Columns["Reference"], "N/A");
                gridView2.SetRowCellValue(iFocusHandle, gridView2.Columns["Amount"], oForm.SelectedAmount);
                gridView2.SetRowCellValue(iFocusHandle, gridView2.Columns["AppliedAmount"], oForm.SelectedAmount);
            }


            if (sDocument == "A/R Credit Memo")
            {
                FND_CASHRECEIPT_ARCM oForm = new FND_CASHRECEIPT_ARCM();

                oForm.ConnectionString = this.ConnectionString;
                oForm.CardCode = txtCustCode.Text;
                oForm.ShowDialog();

                int iFocusHandle = gridView2.FocusedRowHandle;

                gridView2.SetRowCellValue(iFocusHandle, gridView2.Columns["InvoiceNumber"], oForm.SelectedDocumentNumber);
                gridView2.SetRowCellValue(iFocusHandle, gridView2.Columns["Reference"], "N/A");
                gridView2.SetRowCellValue(iFocusHandle, gridView2.Columns["Amount"], Convert.ToDouble(oForm.SelectedAmount) * -1);
                gridView2.SetRowCellValue(iFocusHandle, gridView2.Columns["AppliedAmount"], Convert.ToDouble(oForm.SelectedAmount) * -1);
            }

        }

        private void txtAcctCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            FND_GLACCOUNT oForm = new FND_GLACCOUNT();

            oForm.ConnectionString = this.ConnectionString;
            oForm.ShowDialog();
            
            int iFocusHandle = gridView1.FocusedRowHandle;
            gridView1.SetRowCellValue(iFocusHandle,  gridView1.Columns["AcctCode"],  oForm.SelectedGLAcctCode);
            gridView1.SetRowCellValue(iFocusHandle,  gridView1.Columns["AcctName"],  oForm.SelectedGLAcctName);

        }

        private void txtSalesReturn_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

            FND_RET_CASH_RECEIPT oForm = new FND_RET_CASH_RECEIPT();

            oForm.CustomerCode = txtCustCode.Text;
            oForm.ConnectionString = this.ConnectionString;
            oForm.ShowDialog();

            int iFocusHandle = gridView3.FocusedRowHandle;

            gridView3.SetRowCellValue(iFocusHandle, gridView3.Columns["ReturnNo"], oForm.DocumentNumber);
            gridView3.SetRowCellValue(iFocusHandle, gridView3.Columns["Amount"], oForm.TotalBalance);


        }

        private void gridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                if (MessageBox.Show("Are you sure you want to delete this row?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.Yes)
                {
                    gridView1.DeleteRow(gridView1.FocusedRowHandle);
                    ComputeTotal();
                }
            }

            if (e.KeyCode == Keys.Down)
            {
                if (gridView1.IsLastRow)
                {

                    string sItemCode = "";

                    int iCount = gridView1.FocusedRowHandle;
                    sItemCode = gridView1.GetRowCellValue(iCount, gridView1.Columns["AcctCode"]).ToString();

                    if (sItemCode != "" && (txtStatus.Text != "Closed"))
                    {
                        gridView1.AddNewRow();

                        gridControl1.Select();
                        gridView1.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle;
                        gridView1.FocusedColumn = gridView1.Columns["AcctCode"];
                        gridView1.ShowEditor();


                    }
                    ComputeTotal();
                }
            }
        }

        private void gridView2_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.KeyCode == Keys.Delete)
            {
                if (MessageBox.Show("Are you sure you want to delete this row?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.Yes)
                {
                    gridView2.DeleteRow(gridView2.FocusedRowHandle);
                    ComputeTotal();
                }
            }

            if (e.KeyCode == Keys.Down)
            {
                if (gridView2.IsLastRow)
                {

                    string sItemCode = "";

                    int iCount = gridView2.FocusedRowHandle;
                    sItemCode = gridView2.GetRowCellValue(iCount, gridView2.Columns["InvoiceNumber"]).ToString();

                    if (sItemCode != "" && (txtStatus.Text != "Closed"))
                    {
                        gridView2.AddNewRow();

                        gridControl2.Select();
                        gridView2.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle;
                        gridView2.FocusedColumn = gridView2.Columns["InvoiceNumber"];
                        gridView2.ShowEditor();


                    }
                    ComputeTotal();
                }
            }
        }

        private void gridView3_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.KeyCode == Keys.Delete)
            {
                if (MessageBox.Show("Are you sure you want to delete this row?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == System.Windows.Forms.DialogResult.Yes)
                {
                    gridView3.DeleteRow(gridView3.FocusedRowHandle);
                    ComputeTotal();
                }
            }

            if (e.KeyCode == Keys.Down)
            {
                if (gridView3.IsLastRow)
                {

                    string sItemCode = "";

                    int iCount = gridView3.FocusedRowHandle;
                    sItemCode = gridView3.GetRowCellValue(iCount, gridView3.Columns["ReturnNo"]).ToString();

                    if (sItemCode != "" && (txtStatus.Text != "Closed"))
                    {
                        gridView3.AddNewRow();

                        gridControl3.Select();
                        gridView3.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle;
                        gridView3.FocusedColumn = gridView3.Columns["ReturnNo"];
                        gridView3.ShowEditor();


                    }
                }
                ComputeTotal();
            }
        }

        private void btnCash_Click(object sender, EventArgs e)
        {
            PaymentMeans oForm = new PaymentMeans();

            oForm.DocumentCode = "Petty Cash";
            oForm.ConnectionString = this.ConnectionString;

            oForm.CheckLineItems = this.CheckLineItems;
            if (txtStatus.Text != "Draft")
            {
                oForm.IsReadOnly = true;
            }

            #region Cash Entries
            oForm.CashGLAcctCode = this.CashGLAcctCode;
            oForm.CashGLAcctName = this.CashGLAcctName;
            oForm.CashAmount = Convert.ToDouble(this.CashAmount);
            #endregion

            #region Check Entries
            oForm.CheckGLAcctCode = this.CheckGLAcctCode.ToString();
            oForm.CheckGLAcctName = this.CheckGLAcctName.ToString();
            oForm.CheckAmount = Convert.ToDouble(this.CheckAmount);
            #endregion

            #region Bank Transfer
            oForm.FundTransferAcctCode = this.FundTransferAcctCode;
            oForm.FundTransferAcctName = this.FundTransferAcctName;
            oForm.FundTransferBank = this.FundTransferBank;
            oForm.FundTransferReference = this.FundTransferReference;
            oForm.FundTransferDate = this.FundTransferDate;
            oForm.FundTransferAmount = this.FundTransferAmount;
            #endregion

            oForm.CheckLineItems = this.CheckLineItems;

            oForm.ShowDialog();

            if (oForm.IsCancelled == false)
            {
                #region Cash Entries
                this.CashGLAcctCode = oForm.CashGLAcctCode;
                this.CashGLAcctName = oForm.CashGLAcctName;
                this.CashAmount = Convert.ToDouble(oForm.CashAmount);
                #endregion

                #region Check Entries
                this.CheckGLAcctCode = oForm.CheckGLAcctCode.ToString();
                this.CheckGLAcctName = oForm.CheckGLAcctName.ToString();
                this.CheckAmount = Convert.ToDouble(oForm.CheckAmount);
                #endregion

                #region Bank Transfer
                this.FundTransferAcctCode = oForm.FundTransferAcctCode;
                this.FundTransferAcctName = oForm.FundTransferAcctName;
                this.FundTransferBank = oForm.FundTransferBank;
                this.FundTransferReference = oForm.FundTransferReference;
                this.FundTransferDate = oForm.FundTransferDate;
                this.FundTransferAmount = oForm.FundTransferAmount;
                #endregion

                txtTotalPayment.Text = (this.CashAmount + this.CheckAmount + this.FundTransferAmount).ToString();
            }

            ComputeTotal();
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            PaymentMeans oForm = new PaymentMeans();

            oForm.DocumentCode = "Fund Transfer";
            oForm.ConnectionString = this.ConnectionString;
            oForm.CheckLineItems = this.CheckLineItems;
            if (txtStatus.Text != "Draft")
            {
                oForm.IsReadOnly = true;
            }

            #region Cash Entries
            oForm.CashGLAcctCode = this.CashGLAcctCode;
            oForm.CashGLAcctName = this.CashGLAcctName;
            oForm.CashAmount = Convert.ToDouble(this.CashAmount);
            #endregion

            #region Check Entries
            oForm.CheckGLAcctCode = this.CheckGLAcctCode.ToString();
            oForm.CheckGLAcctName = this.CheckGLAcctName.ToString();
            oForm.CheckAmount = Convert.ToDouble(this.CheckAmount);
            #endregion

            #region Bank Transfer
            oForm.FundTransferAcctCode = this.FundTransferAcctCode;
            oForm.FundTransferAcctName = this.FundTransferAcctName;
            oForm.FundTransferBank = this.FundTransferBank;
            oForm.FundTransferReference = this.FundTransferReference;
            oForm.FundTransferDate = this.FundTransferDate;
            oForm.FundTransferAmount = this.FundTransferAmount;
            #endregion



            oForm.ShowDialog();

            if (oForm.IsCancelled == false)
            {
                #region Cash Entries
                this.CashGLAcctCode = oForm.CashGLAcctCode;
                this.CashGLAcctName = oForm.CashGLAcctName;
                this.CashAmount = Convert.ToDouble(oForm.CashAmount);
                #endregion

                #region Check Entries
                this.CheckGLAcctCode = oForm.CheckGLAcctCode.ToString();
                this.CheckGLAcctName = oForm.CheckGLAcctName.ToString();
                this.CheckAmount = Convert.ToDouble(oForm.CheckAmount);
                #endregion

                #region Bank Transfer
                this.FundTransferAcctCode = oForm.FundTransferAcctCode;
                this.FundTransferAcctName = oForm.FundTransferAcctName;
                this.FundTransferBank = oForm.FundTransferBank;
                this.FundTransferReference = oForm.FundTransferReference;
                this.FundTransferDate = oForm.FundTransferDate;
                this.FundTransferAmount = oForm.FundTransferAmount;
                #endregion

                txtTotalPayment.Text = (this.CashAmount + this.CheckAmount + this.FundTransferAmount).ToString();
            }
            ComputeTotal();
        }

        private void txtCustCode_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void txtTotalBalance_EditValueChanged(object sender, EventArgs e)
        {

        }
    }
}
